<template>
  <el-card shadow="hover">
    <el-row display="flex" justify="center">
      <el-col :span="7"
        ><el-button
          v-btton-iscan="'btn.Attr.add'"
          @click="addTradeMark"
          size="large"
          type="success"
          :icon="Star"
          >添加品牌</el-button
        >
        <el-button
          @click="downloadXlsx"
          size="large"
          type="success"
          :icon="Check"
          >导出Excel</el-button
        ></el-col
      >
    </el-row>

    <el-table border style="margin: 20px 0" :data="reqData">
      <el-table-column type="index" align="center" label="序号" min-width="2" />
      <el-table-column
        prop="tmName"
        align="center"
        label="名称"
        min-width="2"
      />
      <el-table-column align="center" label="LOGO" min-width="4">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="2">
        <template #="{ row, $index }">
          <el-row display="flex" justify="space-around">
            <el-col :span="6">
              <el-button
                type="primary"
                @click="editProduct(row)"
                :icon="Edit"
                v-btton-iscan="'btn.Attr.update'"
                circle
              />
            </el-col>
            <el-col v-btton-iscan="'btn.Attr.remove'" :span="6">
              <el-popconfirm
                width="300"
                :icon="Delete"
                icon-color="red"
                title="确定删除吗？"
                @confirm="delProduct(row.id)"
              >
                <template #reference>
                  <el-button type="danger" :icon="Delete" circle />
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  // eslint-disable-next-line vue/no-parsing-error
  <el-dialog
    v-model="visible"
    :title="addDate.id ? '修改信息' : '添加信息'"
    width="50%"
    align-center
  >
    <el-form
      ref="formRef"
      :label-width="100"
      :model="addDate"
      :rules="rilesData"
    >
      <el-form-item width="200" label="品牌名称:" prop="tmName">
        <el-input
          v-model="addDate.tmName"
          style="height: 40px; width: 80%"
          placeholder="输入品牌名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="logoUrl" label="品牌LOGO:">
        <el-upload
          class="avatar-uploader"
          action="/app-dev/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="addDate.logoUrl" :src="addDate.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogNO">取消</el-button>
        <el-button @click="dialogOK" type="primary"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-pagination
    style="margin: 20px 0"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20]"
    size="large"
    background
    layout=", prev, pager, next,jumper,->,sizes,total"
    :total="total"
  />
</template>
<script setup lang="ts">
import { Star, Check, Edit, Delete } from "@element-plus/icons-vue";
import { onMounted, ref, watch, onUnmounted } from "vue";

import {
  reqProductInfo,
  reqMarkAddORUpdate,
  reqDelProduct,
} from "@/api/product/product";
import type {
  TradeMarkResponseDate,
  Records,
  TradeMark,
} from "@/api/product/type/type";
import { ElMessage } from "element-plus";

//dialog的显示隐藏变量
const visible = ref<boolean>(false);
//分页器当前页
const currentPage = ref<number>(1);
//分页器每页的数量
const pageSize = ref<number>(5);
//请求到的分页器数据总量
const total = ref<number>(0);
//请求到的分页器商品信息数据数组
const reqData = ref<Records>([]);
// 存储按钮权限列表
// const buttonIsCanListRef = computed(() => {
//   return userInfoStore.$state.buttonIsCanList;
// });

//获取el-form表单实例
const formRef = ref<any>();
onMounted(() => {
  reqProductInfoFun();
});
//请求分页器数据函数
const reqProductInfoFun = async () => {
  const res: TradeMarkResponseDate = await reqProductInfo(
    currentPage.value,
    pageSize.value
  );
  total.value = res.total;
  reqData.value = res.records;
};
//监听分页器页码改变
const pageChange = watch(
  [currentPage, pageSize],
  () => {
    reqProductInfoFun();
  },
  {
    immediate: true,
  }
);
//销毁监听器
onUnmounted(() => {
  pageChange();
  // console.log();
});
//添加品牌按钮
const addTradeMark = () => {
  visible.value = true;
  //点击添加按钮清楚之前的校验提示
  formRef.value?.clearValidate("tmName");
  formRef.value?.clearValidate("logoUrl");
  reset();
};
//dialog 谈层中的确认取消按钮
const dialogNO = () => {
  visible.value = false;
};
//dialog的确认按钮
const dialogOK = async () => {
  await formRef.value.validate();

  try {
    reqMarkAddORUpdateFun();
    //重新获取数据
    reqProductInfoFun();
    ElMessage({
      type: "success",
      message: "操作成功",
    });
  } catch {
    ElMessage({
      type: "error",
      message: "操作失败，请重新尝试",
    });
  }

  visible.value = false;
};
//新增信息的数据对象
const addDate = ref<TradeMark>({
  tmName: "",
  logoUrl: "",
});
//自定义品牌名称规则
const tmNamerules = (rules: any, value: any, callback: any) => {
  if (/^[\u4e00-\u9fa5]{2,}$/.test(value)) {
    callback();
  } else {
    callback(new Error("标题必须是2位及以上位数中文"));
  }
};
//图片规则自定义校验
const logoUrlrules = (rules: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error("输入logo图片"));
  }
};
//规则校验
const rilesData = {
  tmName: [{ required: true, trigger: "blur", validator: tmNamerules }],
  logoUrl: [{ required: true, validator: logoUrlrules }],
};

//upload组件上传组件上传图片之前的钩子函数
const beforeAvatarUpload = (fileData: any) => {
  //fileData里面是上传组件的一些信息，类型，大小等
  const imgType = ["image/png", "image/gif", "image/jpeg"];
  if (imgType.includes(fileData.type)) {
    if (fileData.size / 1024 / 1024 > 2) {
      ElMessage({
        type: "error",
        message: "上传的图片的大小不对，不能超过2M",
      });
      return false;
    } else {
      return true;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传的图片类型不对",
    });
    return false;
  }
};
//upload组件上传图片成功后的钩子函数
const handleAvatarSuccess = (response: any) => {
  addDate.value.logoUrl = response.data;
  //因为图片上传el组件只能通过确定按钮校验，这样导致你传入了图片，还会存在上次没传入图片的失败校验
  //所以在这里清除一下校验
  formRef.value.clearValidate("logoUrl");
};
//新增/编辑品牌函数
const reqMarkAddORUpdateFun = async () => {
  await reqMarkAddORUpdate(addDate.value);
};
//编辑按钮
const editProduct = (row: any) => {
  visible.value = true;
  addDate.value.id = row.id;
  addDate.value.logoUrl = row.logoUrl;
  addDate.value.tmName = row.tmName;
};
//清空输入框对象
const reset = () => {
  addDate.value.logoUrl = "";
  addDate.value.tmName = "";
  //服务器数据库id是从1开始的
  addDate.value.id = 0;
};
//删除按钮
const delProduct = async (id: number) => {
  await reqDelProduct(id);
  reqProductInfoFun();
  ElMessage({
    type: "success",
    message: "删除成功",
  });
};
//导出Xlsx表格
import * as XLSX from "xlsx";
const downloadXlsx = () => {
  //将已有数组转换成需要的格式Excel
  const worksheet = XLSX.utils.json_to_sheet(reqData.value);
  //创建新对象用于存储
  const workbook = XLSX.utils.book_new();
  //将转换后的数据加到新变量，命名
  XLSX.utils.book_append_sheet(workbook, worksheet, "boss.xlsx");
  //导出
  XLSX.writeFile(workbook, "Presidents.xlsx");
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.el-dialog {
  margin-top: 100px;
  border-radius: 3%;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
